<?php


namespace app\helper;


/*
 * 用于处理多租户的问题，通过统一的方法来添加租户标识，便于后期的数据库分表
 */

use app\constant\CacheConst;
use app\constant\TenantConst;
use app\libs\Utils;
use app\model\AdminTenant;
use DateTime;
use think\facade\Cache;
use think\facade\Request;

class TenantHelper
{
    /**
     * @param $where
     * @return bool 如果没有tid的话就会返回false
     */
    public static function addTid($where)
    {
        $tid = self::getUserTid();
        if ($tid) {
            $where['tid'] = $tid;
            return $where;
        } else {
            return false;
        }
    }

    /**
     * @return array 用户的信息
     */
    public static function getUserTid()
    {
        $tid = Request::get("tid");
        return $tid;
    }

    /**
     * @param $data {Object} 活动的对象
     * @return mixed {Object} 处理好状态的活动对象
     *
     * @throws
     */
    public static function changeStatus($data)
    {
        $endTime = $data['expiration_time'];
        $endDate = new Datetime($endTime);
        $cDate = new DateTime();
        //判断是否结束
        if ($cDate->getTimestamp() <= $endDate->getTimestamp()) {
            $data['status'] = TenantConst::STATUS_NORMAL;
        } else {
            //结束了
            $data['status'] = TenantConst::STATUS_EXPIRATION;
        }
        return $data;
    }

    /**
     * 设置站点域名缓存,过期时间一天
     * @param $host {String} 站点域名
     * @param $tid {String} 站点id
     * @return bool
     */
    public static function setHostCache($host, $tid)
    {
        $done = Cache::set(CacheConst::TENANT_CACHE_HOST . $tid, $host, 24 * 60 * 60);
        $done1 = Cache::set(CacheConst::HOST_CACHE_TENANT . $host, $tid, 24 * 60 * 60);
        return $done && $done1;
    }

    /**
     * 获取站点域名缓存
     * @param $host {String} 站点域名
     * @return mixed
     */
    public static function getHostCacheTid($host)
    {
        $tid = Cache::get(CacheConst::HOST_CACHE_TENANT . $host);
        if (Utils::isEmpty($tid)) {
            $model = AdminTenant::get(['domain' => $host, 'status' => TenantConst::STATUS_NORMAL]);
            if ($model) {
                self::setHostCache($host, $model->id);
                $tid = $model->id;
            }
        }
        return $tid;
    }

    /**
     * 消除站点域名缓存
     * @param $host {String} 站点域名
     * @param $tid {String} 站点id
     * @return bool
     */
    public static function removeHostCache($host, $tid)
    {
        $done = Cache::rm(CacheConst::TENANT_CACHE_HOST . $tid);
        $done1 = Cache::rm(CacheConst::HOST_CACHE_TENANT . $host);
        return $done && $done1;
    }
}